package com.hetaozi.login.config;

import com.hetaozi.login.entity.SysUser;
import com.hetaozi.login.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @email： wf520200@163.com
 * @date: 2021/11/11 14:20
 * 功能：
 * 描述：
 * @author： 吴帆
 **/
@Slf4j
public class UserRealm  extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 授权认证
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("授权认证...");
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        // 角色
        Set<String> roles = user.getRoles();
        //权限
        Set<String> permissions =user.getPermissions();

        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }


    /**
     * 登陆认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("登陆认证...");
        String username = (String) authenticationToken.getPrincipal();

        SysUser user = sysUserService.getUserByUserName(username);

        if (user == null) {
            // 账号不存在
            throw new UnknownAccountException();
        }

        String salt = user.getSalt();
        return new SimpleAuthenticationInfo(user,
                user.getPassWord(),
                ByteSource.Util.bytes(salt),
                getName());
    }


}
